<!--
 * @Author       : xiaoxiaoguai
 * @Date         : 2025-06-04 11:34:07
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2025-06-26 10:25:12
 * @Description  : 
-->
<template>
	<uv-popup ref="goodDetailModalInner" round="10" mode="bottom" custom-style="height: 73vh;">
		<view class="good-detail-modal">
			<view class="cover" @tap="close">
				<view class="btn-group">
					<uv-icon name="close" color="#fff" size="18"></uv-icon>
				</view>
			</view>
			<scroll-view class="detail" scroll-y :show-scrollbar="false" enhanced>
				<view v-if="good.image" class="image">
					<image :src="good.image"></image>
				</view>
				<view class="wrapper">
					<view class="basic">
						<view class="proName">{{ good.storeName }}</view>
						<view class="tips flex justify-between">
							<view v-html="good.description"></view>
							<!-- <text style="color: red">可获积分:10</text> -->
						</view>
					</view>
					<view class="properties">
						<view
							class="property"
							v-for="(item, index) in good.productAttr"
							:key="index">
							<view class="title">
								<text class="name">{{ item.attrName }}</text>
							</view>
							<view class="values">
								<view
									class="value"
									v-for="(value, key) in item.attrValueArr"
									:key="key"
									:class="{ default: value == newValue[index] }"
									@tap="changePropertyDefault(index, key, false)">
									{{ value }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<view class="actionInner">
					<view class="left">
						<view class="price">
							￥
							<text>{{ good.price }}</text>
						</view>
						<view class="props">
							{{ good.valueStr }}
						</view>
					</view>
					<view class="btn-group">
						<uv-number-box
							v-model="good.number"
							@change="updateNum"
							:min="1"
							:max="100 || good.stock"></uv-number-box>
					</view>
				</view>
				<view
					class="add-to-cart-btn"
					@tap="handleAddToCartInModal"
					:class="{ disabled: good.stock <= 0 }">
					<view>{{ good.stock <= 0 ? '已售罄' : '加入购物车' }}</view>
				</view>
			</view>
		</view>
	</uv-popup>

	<!-- 小球动画 -->
	<view
		:animation="animationY"
		:style="'position:fixed;top:' + ballY + 'px;z-index:' + dynamicZIndex"
		v-if="showBall">
		<view class="ball" :animation="animationX" :style="'position:fixed;left:' + ballX + 'px;'">
			<image class="ball" :src="addImg" mode=""></image>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, watch, nextTick, getCurrentInstance, onMounted } from 'vue'
	import { useMixin } from '@/utils/mixins'

	const { checkStockIsEnough, seeStock } = useMixin() // 使用 composable
	const popupRef = ref(null)
	const props = defineProps({
		good: Object,
		newValue: Array,
	})
	const dynamicZIndex = ref(-1)
	const categoryId = ref('')
	const open = () => {
		goodDetailModalInner.value.open()
	}
	const close = () => {
		goodDetailModalInner.value.close() // 关闭弹窗逻辑
		categoryId.value = ''
		good.value = {}
	}
	const goodDetailModalInner = ref()
	const good = ref({})
	const currentObj = ref({})
	const init = async (newGood, obj) => {
		currentObj.value = obj
		const goodObj = await seeStock(newGood.id)
		good.value = JSON.parse(
			JSON.stringify({
				...goodObj,
				number: 1,
			})
		)
		categoryId.value = newGood.cateId
		changePropertyDefault(0, 0, true)
		open()
	}
	const newValue = ref([])
	const changePropertyDefault = (index, key, isDefault) => {
		//改变默认属性值
		let valueStr = ''
		if (isDefault) {
			newValue.value = []
			for (let i = 0; i < good.value.productAttr.length; i++) {
				newValue.value[i] = good.value.productAttr[i].attrValueArr[0]
			}
		} else {
			newValue.value[index] = good.value.productAttr[index].attrValueArr[key]
		}
		valueStr = newValue.value.join(',')
		let productValue = good.value.productValue[valueStr]
		if (!productValue) {
			let skukey = JSON.parse(JSON.stringify(newValue.value))
			skukey.sort((a, b) => a.localeCompare(b))
			console.log('skukey:', skukey)
			valueStr = skukey.join(',')
			productValue = good.value.productValue[valueStr]
		}
		console.log('productValue:', productValue)
		good.value.number = 1
		good.value.price = parseFloat(productValue.price).toFixed(2)
		good.value.stock = productValue.stock
		// good.value.image = productValue.image ? productValue.image : good.value.image
		// good.value.image = good.value.image
		good.value.valueStr = valueStr
	}
	const updateNum = e => {
		console.log('updateNum:', e)
		//更新商品数量
		good.value.number = e.value
	}

	const handleAddToCart = (categoryId, newGood, num) => {
		//添加到购物车
		const index = props.cart.findIndex(item => {
			if (newGood) {
				return item.id === newGood.id && item.valueStr === good.value.valueStr
			} else {
				return item.id === newGood.id
			}
		})
		if (index > -1) {
			props.cart[index].number += num
		} else {
			props.cart.push({
				id: newGood.id,
				cate_id: categoryId,
				name: newGood.storeName,
				price: newGood.price,
				number: num,
				image: newGood.image,
				valueStr: good.value.valueStr,
			})
		}
		uni.setStorageSync('cart', JSON.parse(JSON.stringify(props.cart)))
	}
	const emit = defineEmits(['getCartBarInfo'])
	const handleAddToCartInModal = async () => {
		if (!(await checkStockIsEnough(good.value, good.value.number, props.cart))) {
			return
		}

		console.log('good.value', good.value)
		if (good.value.stock <= 0) {
			uni.showToast({
				title: '商品已售罄',
				icon: 'none',
			})
			return
		}
		let goodValue = JSON.parse(JSON.stringify(good.value))
		handleAddToCart(categoryId.value, good.value, good.value.number)
		close()
		emit('getCartBarInfo')
		dynamicZIndex.value = 9999999
		setTimeout(() => {
			setAnimation(goodValue)
		}, 100)
		// sendTestMessage()
	}
	onMounted(() => {
		// 首次真机卡顿问题--fix
		dynamicZIndex.value = -1
		setAnimation({})
	})
	// 动画相关
	const shoppingCartAnimation = ref(false)
	const showBall = ref(false)
	const animationY = ref('')
	const animationX = ref('')
	const ballY = ref('')
	const ballX = ref('')
	const addImg = ref('')
	const setAnimation = async item => {
		console.log('开始执行动画')
		addImg.value = item.image
		nextTick(() => {
			let imgX = currentObj.value.left - 15
			let imgY = currentObj.value.top - 15
			let ballX_ = imgX
			let ballY_ = imgY
			createAnimation(ballX_, ballY_)
		})
	}
	// 延迟执行
	const setDelayTime = sec => {
		return new Promise(resolve => {
			setTimeout(() => {
				resolve()
			}, sec)
		})
	}
	const cartBarInfoCopy = ref({})
	// 创建动画
	const createAnimation = async (ballX_, ballY_) => {
		// uni.getSystemInfo({
		// 	success: async () => {
		console.log(cartBarInfoCopy.value, 'props.cartBarInfoCopy')
		let bottomX = cartBarInfoCopy.value.left
		let bottomY = cartBarInfoCopy.value.top
		let animationX_ = flyX(bottomX, ballX_)
		let animationY_ = flyY(bottomY, ballY_)
		// 获取放大缩小的动画
		let scaleAnimation_ = await createScaleAnimation();

		ballX.value = ballX_
		ballY.value = ballY_
		showBall.value = true
		// 将 scaleAnimation 应用到 animationX 或 animationY 上
		animationX.value = scaleAnimation_.export(); // 或者 animationY.value = scaleAnimation_.export()
		await setDelayTime(100)
		animationX.value = animationX_.export()
		animationY.value = animationY_.export()
		await setDelayTime(400)

		animationX.value = flyX(0, 0, 0).export()
		animationY.value = flyY(0, 0, 0).export()
		showBall.value = false
		shoppingCartAnimation.value = true

		await setDelayTime(700)
		shoppingCartAnimation.value = false
		// 	},
		// })
	}

	// 水平动画
	const flyX = (bottomX, ballX_, duration) => {
		let animation = uni.createAnimation({
			duration: duration || 400,
			timingFunction: 'linear',
		})
		// 先放大，再缩小
		animation.translateX(bottomX - ballX_).step()
		return animation
	}

	// 创建放大缩小的动画
	const createScaleAnimation = async () => {
		let scaleAnimation = uni.createAnimation({
			duration: 200, // 设置放大缩小的时长
			timingFunction: 'ease-in-out', // 设置缓动效果
		})

		// 先放大，再缩小
		scaleAnimation.scale(2).step() // 放大
		scaleAnimation.scale(1).step() // 缩小

		return scaleAnimation
	}

	// 垂直动画
	const flyY = (bottomY, ballY_, duration) => {
		let animation = uni.createAnimation({
			duration: duration || 400,
			timingFunction: 'ease-in',
		})
		animation.translateY(bottomY - ballY_).step()
		return animation
	}
	// 暴露方法
	defineExpose({
		init,
		cartBarInfoCopy,
	})
</script>

<style scoped lang="scss">
	.good-detail-modal {
		position: relative;
		background: #fff;
		border-radius: 10rpx 10rpx 0 0;
		height: 100%;
		.detail {
			padding-bottom: 240rpx;
			height: 100%;
		}
	}
	.cover {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		z-index: 99999999;
		.btn-group {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 8rpx;
			width: 50rpx;
			height: 50rpx;
			background-color: #bfbebe;
			border-radius: 50%;
		}
	}
	.image image {
		width: 100%;
		height: 450rpx;
	}
	.wrapper {
		padding: 20rpx;
		.basic {
			padding-bottom: 15rpx;
			border-bottom: 1px solid #eee;
			.tips {
				font-size: 26rpx;
				color: #999;
			}
		}
	}
	.proName {
		font-size: 32rpx;
		font-weight: bold;
		color: #000;
		margin-bottom: 10rpx;
	}
	.property {
		margin-bottom: 30rpx;
		.name {
			font-size: 28rpx;
			color: #666;
		}
		.values {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			margin-top: 15rpx;
		}
		&:last-child {
			margin-bottom: 0;
		}
	}
	.value {
		padding: 10rpx 25rpx;
		color: #333;
		font-size: 26rpx;
		border-radius: 6rpx;
		background-color: #f5f5f5;
	}
	.value.default {
		background: $qingzhen-btn-primary-color;
		color: #fff;
	}
	.action {
		padding: 20rpx 30rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		height: 240rpx;
		display: flex;
		flex-direction: column;
		width: 100%;
		// border-top: 1px solid #eee;
		box-shadow: 0 -2px 3px -1px rgba(0, 0, 0, 0.2);
		.actionInner {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.btn-group {
				display: flex;
				align-items: center;
				.uv-number-box {
					border: 1px solid $qingzhen-btn-primary-color;
					border-radius: 10rpx;
				}
			}
			.price {
				font-size: 22rpx;
				text {
					font-size: 34rpx;
					font-weight: bold;
				}
			}
			.props {
				font-size: 24rpx;
			}
		}
	}

	.add-to-cart-btn {
		margin-top: auto;
		margin-bottom: 20rpx;
		background: $qingzhen-btn-primary-color;
		color: #fff;
		text-align: center;
		padding: 20rpx 0;
		font-size: 32rpx;
		border-radius: 100rpx;
	}

	.disabled {
		background: #ccc !important;
		color: #666 !important;
	}

	.ball {
		height: 30px;
		width: 30px;
		border-radius: 50rpx;
		position: fixed;
	}
</style>
